//
//  TopicAddNewViewController.swift
//  Venus
//
//  Created by Smith_Yang on 2018/8/6.
//  Copyright © 2018 zhaowang. All rights reserved.
//

import UIKit

import Photos
import SwiftyJSON

class TopicAddNewViewController: BaseViewController {
    
    @IBOutlet weak var confirmButton: UIButton!
    
    @IBOutlet weak var topicDetailTextView: RichEditorView!
    
    @IBOutlet weak var mimoButton: UIButton!
    
    @IBOutlet weak var pictureButton: UIButton!
    
    @IBOutlet weak var selectGroup: UIButton!
   
    @IBOutlet weak var titleTextFiled: UITextField!
    
    @IBOutlet weak var detailBg: UIView!
    @IBOutlet weak var selectGroupBg: UIView!
    @IBOutlet weak var titleBg: UIView!
    
    @IBOutlet weak var scanBgView: UIView!
    @IBOutlet weak var scanSubBg: UIView!
    @IBOutlet weak var scanButton: UIButton!
    
    
    @IBOutlet weak var pcWebLink: UILabel!
    
    
    fileprivate var uploadImgArr:[UIImage] = [UIImage]()
    fileprivate var tempUploadImgArr:[String] = [String]()

    var selectedGroupMode: TopicGroupModel?
    var currentModel: TopicModel?
    var imageSize : CGSize = CGSize.zero
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "添加话题"

        setupUI()
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    @IBAction func scanQRAction(_ sender: Any) {
        
        let QRScanVc = QRScanViewController()
        self.navigationController?.pushViewController(QRScanVc, animated: true)

    }
    
    @IBAction func selectGroupAction(_ sender: Any) {
        
        let selectGroupVC = GroupSelectionViewController();
        
        selectGroupVC.selectedGroup { (model) in
            self.selectedGroupMode = model
            
            self.selectGroup.setTitle(model.groupName, for: .normal)
            
        }
        
        self.navigationController?.pushViewController(selectGroupVC, animated: true)
        
    }
    
    @IBAction func insertImageAction(_ sender: Any) {
        
        openImagePicker()
    }
    
    @IBAction func insertEmojiAction(_ sender: Any) {
    }
    
    @IBAction func confirmAction(_ sender: Any) {
        
        guard let title = titleTextFiled.text else {
            hudLoadMessage("请输入文章名称。")
            return
        }
        
        guard let groupId = selectedGroupMode?.id else {
            hudLoadMessage("请选择发表文章的小组。")
            return
        }
        
        guard topicDetailTextView.contentHTML.count > 0  else {
            hudLoadMessage("请输入文章内容。")
            return
        }
        
        let current = String().currentTime()
        let dict = [
            "article": topicDetailTextView.contentHTML,
            "authorId": UserInfo.shareInstance.userModel().id,
            "groupId": groupId,
            "type": "00",
            "title": title ] as [String : Any]
        let api = kHost + kaddNewTopicList + "".apiF(time: current, sign: "")
        self.hudLoad()
        TempNetTool.post(api, parameters: dict, progress: nil, success: { [weak self] (result) in
            self?.hudHide()
            
            self?.navigationController?.popViewController(animated: true)
        }) {  [weak self](error) in
            self?.hudHide()
            self?.hudLoadMessage("error")
        }
    }
    
}



// MARK:- 图片代理
extension TopicAddNewViewController:UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    fileprivate func photoClick() {
        if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary)  { return }
        let photoVc = UIImagePickerController()
        photoVc.sourceType = .photoLibrary
        photoVc.delegate = self
        present(photoVc, animated: true, completion: nil)
    }
    
    fileprivate func cameraClick() {
        let pick:UIImagePickerController = UIImagePickerController()
        pick.delegate = self
        pick.sourceType = UIImagePickerController.SourceType.camera
        pick.allowsEditing = true
        present(pick, animated: true, completion: nil)
        
    }
    func openImagePicker() {
        let alertVc = UIAlertController(title: "选择来源?", message: nil, preferredStyle: .actionSheet)
        let photoAction = UIAlertAction(title: "从相册选取", style: .default) { (_) in
            self.photoClick()
        }
        let cameraAction = UIAlertAction(title: "相机", style: .default) { (_) in
            self.cameraClick()
        }
        let cancelAction = UIAlertAction(title: "取消", style: .default) { (_) in}
        alertVc.addAction(photoAction)
        alertVc.addAction(cameraAction)
        alertVc.addAction(cancelAction)
        present(alertVc, animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true, completion: nil)
        
        guard let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else { return }
        imageSize = image.size
        let imageData:Data = image.jpegData(compressionQuality: 0.5)!
        
        self.hudLoad("上传中 请稍后")
        TempNetTool.get(kHost + kgetImgToken, parameters: ["timestamp":"11","sign":"22"], progress: nil, success: { (result) in
            let json = JSON(result ?? "")
            let token = json["uptoken"].string
            let upManager = QNUploadManager()
            upManager?.put(imageData, key: nil, token: token, complete: { [unowned self](info, key, resp) in
                self.hudHide()
                let json = JSON(resp as Any)
                let url = json["key"].stringValue
                if url.count > 0 {
                    var maxW = 0
                    if self.imageSize.width > kScreenW - 20 {
                        maxW = Int(kScreenW - 20)
                    }else {
                        maxW = Int(self.imageSize.width)
                    }
                    let height = CGFloat(maxW) * self.imageSize.height /  self.imageSize.width
                    
                 //   self.topicDetailTextView.insertImageSize(kqnImageHost + url, alt: "图片", width: String(maxW), height: String(Int(height)))
                }else {
                    self.hudLoadMessage("网络异常")
                }
                
                }, option: nil)
        }) { [weak self](error) in
            self?.hudHide()
            self?.hudLoadMessage("网络异常")
        }
    }
    
    
}

extension TopicAddNewViewController {
    
    func setupUI()  {
        
        let button = UIButton(type: .custom)
        button.addTarget(self, action: #selector(barQAction), for: UIControl.Event.touchUpInside)
        button.setImage(UIImage(named: "icon_scan"), for: .normal)
        button.frame = CGRect(x: 10, y: 0, width: 36, height: 36)
        
        let barBarButton = UIBarButtonItem(customView: button)
        navgationBar.items?.first?.rightBarButtonItem = barBarButton
        
        detailBg.layer.cornerRadius = 5
        
        selectGroupBg.layer.cornerRadius = 5
    
        titleBg.layer.cornerRadius = 5
        
        let tapGuesture = UITapGestureRecognizer(target: self, action: #selector(tapAction))
        scanBgView.addGestureRecognizer(tapGuesture)

        scanSubBg.layer.cornerRadius = 5
        
        scanButton.layer.cornerRadius = 5
        
        topicDetailTextView.layer.cornerRadius = 3
        topicDetailTextView.placeholder = "请输入文章详情。。。"

        scanBgView.alpha = 0
        
        pcWebLink.text = kHost + "/project-api/pcTopic"
        
        confirmButton.layer.cornerRadius = confirmButton.frame.size.height/2.0
        
    }
    
    @objc func barQAction(){
        view.endEditing(true)
        scanBgView.alpha = 1
        
    }
    
    @objc func tapAction(){
        
        scanBgView.alpha = 0
    }
    
}
